import java.util.concurrent.Semaphore;

/**
 * Created by admin on 2019/1/17.
 */

public class SemaphoreTest {
    /**
     * 线程执行类，每次存10块钱
     */
    static class NewThread implements Runnable {
        private Semaphore semaphore;

        public NewThread(Semaphore semaphore) {
            this.semaphore = semaphore;
        }

        public void run() {
            try {
                semaphore.acquire();
                System.out.println("线程" + Thread.currentThread().getName() + "正在工作===========");
                Thread.sleep(1000);
                System.out.println("线程" + Thread.currentThread().getName() + "工作完了");
                semaphore.release();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) throws InterruptedException {
        // 定义2个新号量，同时只有两人工作
        Semaphore semaphore = new Semaphore(2);
        // 建立10个线程
        for (int i = 0; i < 10; i++) {
            // 执行一个线程
            new Thread(new NewThread(semaphore)).start();
        }
        semaphore.acquireUninterruptibly(2);
        System.out.println("大家休息一下==========");
        Thread.sleep(2000);
        System.out.println("休息好了，继续工作==========");
        semaphore.release(2);
    }
}
